package com.company.planner.web.screens.hotwords;

import com.company.planner.entity.HotWords;
import com.company.planner.entity.SwitchEnum;
import com.company.planner.service.ExcelService;
import com.company.planner.service.WordsService;
import com.google.common.collect.Lists;
import com.haulmont.cuba.core.global.DataManager;
import com.haulmont.cuba.gui.Dialogs;
import com.haulmont.cuba.gui.Notifications;
import com.haulmont.cuba.gui.ScreenBuilders;
import com.haulmont.cuba.gui.app.core.inputdialog.DialogActions;
import com.haulmont.cuba.gui.app.core.inputdialog.DialogOutcome;
import com.haulmont.cuba.gui.components.Button;
import com.haulmont.cuba.gui.components.DataGrid;
import com.haulmont.cuba.gui.components.FileUploadField;
import com.haulmont.cuba.gui.model.CollectionLoader;
import com.haulmont.cuba.gui.screen.*;
import com.haulmont.cuba.gui.upload.FileUploadingAPI;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.slf4j.Logger;

import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@UiController("planner_HotWords.browse")
@UiDescriptor("hot-words-browse.xml")
@LookupComponent("hotWordsDataGrid")
@LoadDataBeforeShow
public class HotWordsBrowse extends StandardLookup<HotWords> {

    @Inject
    private FileUploadingAPI fileUploadingAPI;

    @Inject
    private FileUploadField upload;
    @Inject
    private Notifications notifications;
    @Inject
    private ExcelService excelService;
    @Inject
    private CollectionLoader<HotWords> hotWordsesDl;
    @Inject
    private DataManager dataManager;
    @Inject
    private ScreenBuilders screenBuilders;
    @Inject
    private DataGrid<HotWords> hotWordsDataGrid;
    @Inject
    private Dialogs dialogs;
    @Inject
    private WordsService wordsService;
    @Inject
    private Logger log;

    @Subscribe("upload")
    public void onUploadFileUploadSucceed(FileUploadField.FileUploadSucceedEvent event) {
        int beginRow = 0;
        int beginColumn = 0;
        Integer endRow;
        int endColumn = 1;
        String sheetName = "word";

        try {
            File file = fileUploadingAPI.getFile(upload.getFileId());
            endRow = excelService.getLastColl(file, sheetName, beginColumn, beginRow);
            if (endRow != null) {
                String[][] result = excelService.readExcelFile(file, sheetName, beginRow, beginColumn, endRow, endColumn);
                for (String[] strings : result) {
                    try {
                        HotWords hotWords = dataManager.create(HotWords.class);
                        hotWords.setWord(strings[0]);
                        hotWords.setSwitchState(SwitchEnum.OFF);
                        dataManager.commit(hotWords);
                    } catch (Exception e) {
                        log.error("Error", e);
                    }
                }
                hotWordsesDl.load();
                notifications.create(Notifications.NotificationType.HUMANIZED).withCaption("导入成功...").show();
            } else {
                notifications.create(Notifications.NotificationType.HUMANIZED).withCaption("没有数据").show();
            }
        } catch (IOException e) {
            notifications.create(Notifications.NotificationType.HUMANIZED).withCaption("文件读取异常").show();
        } catch (InvalidFormatException e) {
            notifications.create(Notifications.NotificationType.HUMANIZED).withCaption("解析异常").show();
        } catch (Exception e) {
            notifications.create(Notifications.NotificationType.HUMANIZED).withCaption(e.getMessage() != null ? e.getMessage() : "上传失败").show();
        }

    }


    @Subscribe("createBtn")
    public void onCreateBtnClick1(Button.ClickEvent event) {
        screenBuilders.editor(hotWordsDataGrid)
                .newEntity()
                .withScreenId("planner_HotWords.create")
                .build()
                .show();
    }


    /**
     * 获取在列表中选中的项
     *
     * @return List<HotWords>
     */
    public List<HotWords> getSelected() {
        Iterator<HotWords> wordsIterator = hotWordsDataGrid.getSelected().iterator();
        List<HotWords> hotWords = new ArrayList<>();
        while (wordsIterator.hasNext()) {
            hotWords.add(wordsIterator.next());
        }
        return hotWords;
    }

    @Subscribe("removeBtn")
    public void onRemoveBtnClick(Button.ClickEvent event) {
        dialogs.createInputDialog(this)
                .withCaption("确认删除选中元素?")
                .withActions(DialogActions.OK_CANCEL)
                .withCloseListener(closeEvent -> {
                    if (closeEvent.closedWith(DialogOutcome.OK)) {
                        List<HotWords> hotWords = getSelected();
                        wordsService.batchOperationRecord(hotWords, SwitchEnum.OFF.getId());
                        wordsService.batchDelHotWords(hotWords);
                        //刷新当前DataSource
                        hotWordsesDl.load();
                    }
                })
                .show();
    }

    @Subscribe("hotWordsDataGrid")
    public void onHotWordsDataGridEditorPostCommit(DataGrid.EditorPostCommitEvent event) {
        HotWords item = (HotWords) event.getItem();
        log.info("post commit id:{} || word:{}", item.getId(), item.getWord());
        if (item.getSwitchState() != null) {
            if (item.getSwitchState().equals(SwitchEnum.OFF)) {
                wordsService.batchOperationRecord(Lists.newArrayList(item), SwitchEnum.OFF.getId());
            } else {
                wordsService.batchOperationRecord(Lists.newArrayList(item), SwitchEnum.ON.getId());
            }
            dataManager.commit(item);
        } else {
            notifications.create(Notifications.NotificationType.TRAY)
                    .withCaption("不能将开关修改为空")
                    .show();
        }
    }


}